import re

import requests
import json

from myapp.entities.Consultation import Consultation

API_Key = '6XUa10kSl6lDCokWvACoWeKL'
Secret_Key = '2Cef6J4fVjG4lKwjoSk1hTC1T1DTrkCT'
gpt_url = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token='


def get_access_token():
    """
    使用 API Key，Secret Key 获取access_token，替换下列示例中的应用API Key、应用Secret Key
    """

    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + API_Key + "&client_secret=" + Secret_Key

    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")


def test():
    url = gpt_url + get_access_token()

    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": "你好"
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    print(response.text)

    return response.json().get('result')


def stream():
    url = gpt_url + get_access_token()

    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": "你好"
            }
        ],
        "stream": True
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload, stream=True)

    return response


def handleLine_todict(line):
    data_str = line.decode('utf-8')
    match = re.search(r'data: (.*)', data_str)
    if match:
        json_string = match.group(1).strip()  # 去除字符串开头和结尾的空白字符
        try:
            # 解析JSON字符串为Python字典
            data_dict = json.loads(json_string)
            return data_dict
        except json.JSONDecodeError as e:
            print(f"JSON解析错误: {e}")
            return None
    else:
        return None


# 提问
def question(userid, consultationid, question):
    url = gpt_url + get_access_token()
    consultation = Consultation.query.filter_by(userid=userid, consultationid=consultationid).first()
    consultation.add_question(question)
    messages = consultation.get_content_dict()

    payload = json.dumps({'messages': messages, 'stream': True})
    headers = {'Content-Type': 'application/json'}
    response = requests.request("POST", url, headers=headers, data=payload, stream=True)

    return response

